package impl

import (
	"github.com/jinzhu/gorm"
	"go-test/model"
	"go-test/reposiroty"
)

type CourseRepositoryImpl struct {
}

func NewCourseRepository() reposiroty.CourseRepository {
	return &CourseRepositoryImpl{}
}

/*
写法参考 https://learnku.com/docs/gorm/v1
*/

func (c *CourseRepositoryImpl) CreateCourse(course *model.Course, db *gorm.DB) (int64, error) {
	// db.model 是固定写法，与表字段映射的对象
	result := db.Model(&model.Course{}).Create(course)
	if result.Error != nil {
		return 0, result.Error
	}

	return result.RowsAffected, nil
}

func (c *CourseRepositoryImpl) ListCourse(db *gorm.DB) ([]*model.Course, error) {
	list := make([]*model.Course, 0)

	result := db.Model(&model.Course{}).Find(&list)

	if result.Error != nil {
		return nil, result.Error
	}

	return list, nil
}

func (c *CourseRepositoryImpl) DelCourse(courseId string, db *gorm.DB) (int64, error) {
	result := db.Model(&model.Course{}).Where("course_id = ?", courseId).Delete(&model.Course{})

	if result.Error != nil {
		return 0, result.Error
	}

	return result.RowsAffected, nil
}

func (c *CourseRepositoryImpl) UpdateCourse(courseId string, name string, db *gorm.DB) (int64, error) {
	// 需要更新什么字段，写在map结构里面
	m := map[string]interface{}{
		"name": name,
	}
	result := db.Model(&model.Course{}).Where("course_id = ?", courseId).Updates(m)

	if result.Error != nil {
		return 0, result.Error
	}

	return result.RowsAffected, nil
}
